package com.ruoyi.web.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.KdniaoApiUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.core.domain.Orders;
import com.ruoyi.core.domain.WxUserInfo;
import com.ruoyi.core.service.IGiftCardService;
import com.ruoyi.core.service.IOrdersService;
import com.ruoyi.core.service.impl.WeixinService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * @author lgc
 * @createDate 2020/8/20 - 10:13
 */
@RestController
@RequestMapping("/wx/json")
public class WxJsonController extends BaseController {

   @Autowired
   private IGiftCardService giftCardService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private WxMpService wxMpService;


    /**
     * 防伪认证
     * @return
     */
    @PostMapping("/validateCode")
    public AjaxResult validateCode(String code)
    {
        testValidateCode();//验证验证码
        Long userId = getUserId();
        //防伪验证
        giftCardService.checkCodes(code,userId);
        return success("该提货码真实存在");
    }

    /**
     * 提货码密码验证
     * @return
     */
    @PostMapping("/testCode")
    public AjaxResult testCode(HttpSession session, String code, String password)
    {
        testValidateCode();//验证验证码
        Long userId =getUserId();
        Long cardId = giftCardService.testCode(code,password,userId);

        StringBuilder sb = new StringBuilder(20);
        sb.append(Constants.CARDID_CODE).append(":").append(cardId);
        //创建4位数的验证码(随机,唯一)
        String codes = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);

        session.setAttribute(sb.toString(),codes);
        return AjaxResult.success(cardId);
    }
    /**
     * 快递鸟订单查询物流信息
     * @return
     */
    @PostMapping("/logisticsMsg")
    public AjaxResult logistics(String expressNumber)
    {
        String result = ordersService.getLogisticsMsgByNumber(expressNumber);
        if (result==null){
            AjaxResult.error("查询有误，请联系管理员");
        }
        if (result.equals("已逾期查询")){
            AjaxResult.warn(result);
        }
        return AjaxResult.success(JSONObject.parseObject(result));
    }

    /**
     * 使用提货卡录入信息
     * @return
     */
    @PostMapping("/addOrders")
    @Transactional
    public synchronized AjaxResult addOrders(Orders orders, HttpSession session)
    {
        testValidateCode();//验证码验证
        WxUserInfo userInfo =(WxUserInfo)
                Optional.ofNullable(session
                .getAttribute(Constants.WX_USER))
                .orElseThrow(()->new BusinessException("请使用微信授权"));

        StringBuilder sb = new StringBuilder(20);
        sb.append(Constants.CARDID_CODE).append(":").append(orders.getGiftCardId());
        Optional.ofNullable(session.getAttribute(sb.toString()))
                .orElseThrow(()->new BusinessException("请进行码验证！"));


        Long userId = getUserId();
        orders.setCreatedBy(userId);
        orders.setOpenId(userInfo.getOpenId());
        orders = ordersService.insertOrders(orders);

        //删除认证礼品卡Id
        session.removeAttribute(sb.toString());

       /* //发送模版消息提醒
        weixinService.sendMsg(wxMpService,templateId,orders,userId,userInfo.getOpenId());*/
        return AjaxResult.success(orders);
    }

    /**
     * @Author lgc
     * @Date 2020年08月20日 下午10:13
     *
     * @Description 获取扫一扫参数
     */
    @GetMapping("/scan")
    public AjaxResult getScanParam(String url) {
        System.out.println("url = " + url);
        try {
            WxJsapiSignature scanParam = weixinService.getScanParam(wxMpService, url);
            System.out.println("scanParam = " + scanParam);
            return AjaxResult.success("获取扫一扫参数成功",scanParam);
        } catch (Exception e) {
            return error("获取扫一扫参数失败");
        }
    }
}
